package com.tango.tangoapp.arealearning;

import android.content.Context;
import android.os.AsyncTask;

import com.google.atap.tangoservice.Tango;
import com.google.atap.tangoservice.TangoAreaDescriptionMetaData;
import com.google.atap.tangoservice.TangoErrorException;
import com.google.atap.tangoservice.TangoInvalidException;

/**
 * Created by black on 2017/7/15.
 */

/**
 * Save the ADF in the background
 */
public class SaveAdfTask extends AsyncTask<Void,Integer,String> {
    public interface SaveAdfListener{
        void onSaveAdfFail(String adfName);
        void onSaveAdfSuccess(String adfName,String adfUuid);
    }

    Context mContext;
    SaveAdfListener mCallbackListener;
    SaveAdfDialog mPrograssDialog;
    Tango mTango;
    String mAdfName;

    public SaveAdfTask(Context context,SaveAdfListener callbackListener,Tango tango,String adfName){
        mContext=context;
        mCallbackListener=callbackListener;
        mTango=tango;
        mAdfName=adfName;
        mPrograssDialog=new SaveAdfDialog(context);
    }

    @Override
    protected String doInBackground(Void... params){
        String adfUuid=null;

        try{
            //  Save the ADF
            adfUuid=mTango.saveAreaDescription();

            TangoAreaDescriptionMetaData metaData=mTango.loadAreaDescriptionMetaData(adfUuid);
            metaData.set(TangoAreaDescriptionMetaData.KEY_NAME,mAdfName.getBytes());
            mTango.saveAreaDescriptionMetadata(adfUuid,metaData);
        }catch (TangoErrorException e){
            adfUuid=null;
        }catch (TangoInvalidException e){
            adfUuid=null;
        }

        return adfUuid;
    }

    /**
     * Set up the progress dialog.
     */
    @Override
    protected void onPreExecute(){
        if(mPrograssDialog!=null)
            mPrograssDialog.show();
    }

    /**
     * Responds to progress update event to updating the UI.
     */
    @Override
    protected void onProgressUpdate(Integer... progress){
        if(mPrograssDialog!=null)
            mPrograssDialog.setProgress(progress[0]);
    }

    /**
     * Dismiss the progress dialog and call the activity.
     */
    @Override
    protected void onPostExecute(String adfUuid){
        if(mPrograssDialog!=null)
            mPrograssDialog.dismiss();
        if(mCallbackListener!=null){
            if(adfUuid!=null)
                mCallbackListener.onSaveAdfFail(mAdfName);
            else
                mCallbackListener.onSaveAdfSuccess(mAdfName,adfUuid);
        }
    }
}
